#!/bin/bash
# Author: liuxu
# Date: 2025/8/27
# Description: dudiag自动化测试脚本
# Usage method:
#    nohup bash ./dudiag-benchmark-test.sh  > dudiag_test_results-`date +"%Y%m%d"`.log 2>&1 && zip -r ../test_dudiag_result-bw150.zip dudiag_test_results-*.log result &

########################################################################################################################
# 检测是否在工具同目录运行
EXE_FILE="dudiag"
if [ ! -f "${EXE_FILE}" ]; then  # 检测测试工具是否在当前目录
  echo -e "\033[31m[ERROR] The '${EXE_FILE}' file was not found in the current directory! \033[0m"
  exit 1
fi

# 检测加载的环境变量是否正确
[ -z "$ROCM_PATH" ] && { echo "[ERROR] The ROCM_PATH environment variable is not source"; exit 1; }
[[ "$ROCM_PATH" != *dtk* ]] && { echo "[ERROR] ROCM_PATH is not a dtk environment ($ROCM_PATH)"; exit 2; }



echo "==========Obtain the current environmental information=========="
# 记录环境相关信息
env_commands=(
    # 获取本地IP地址
    "ip addr | grep inet | grep -vE 'inet6|127.0.0.1' | awk '{print \$2}'"

    # 查看操作系统
    "cat /etc/system-release"

    # 查看内核信息
    "uname -a"

    # 查看驱动版本信息
    "/opt/hyhal/bin/hy-smi --showdriverversion"

    # 查看dcu平台
    "/opt/hyhal/bin/hy-smi --showproductname"

    # 查看当前频率
    "hy-smi -c"

    # 查看卡
    "/opt/hyhal/bin/hy-smi"
)


# 循环执行环境信息收集命令
for env_cmd in "${env_commands[@]}"; do
    # 移除首尾空格
    trimmed_cmd=$(echo "$env_cmd" | xargs)

    # 跳过空行和以#开头的注释行
    if [[ -z "$trimmed_cmd" || "$trimmed_cmd" == \#* ]]; then
        continue
    fi

    # 执行命令并打印
    echo -e "\n========== 执行命令: $trimmed_cmd =========="
    eval "$trimmed_cmd"
done

########################################################################################################################
echo "==========Execute the test command=========="
# 记录测试开始时间
echo -e "\n========== Start test time: $(date +"%Y-%m-%d %H:%M:%S") =========="

# 定义要执行的命令数组，每个元素是命令及其注释（注释部分用于记录，实际执行时会去掉）
commands=(
    "./dudiag 1,300  # Thermal Core Qualification Test"
    "./dudiag 2,300  # Thermal Mem Qualification Test"
    "./dudiag 3,300  # Thermal Core and Mem Qualification Test"
    "./dudiag 4  # PCIe Bandwidth Test"
    "./dudiag 5  # xHCL Bandwidth Test"
    "./dudiag 6  # Mem  Bandwidth Test"
    "./dudiag 7  # Peak Performance Test"
#    "./dudiag 8  # Gemmperf Stress Test"
    "./dudiag h  # DUQual Version"
    "./dudiag t  # Generate System Topology"
    "./dudiag q  # Quit DUQual"
)

for cmd_info in "${commands[@]}"; do
    # 提取实际要执行的命令，去掉注释部分（假设注释以 # 开头）
    cmd=$(echo "$cmd_info" | awk '{print $1, $2}')  # 简单处理，按空格分割取前两部分，可根据实际命令调整
    # 打印要执行的命令到结果文件和控制台
    echo -e "\n========== ($(date +"%Y-%m-%d %H:%M:%S"))执行命令: $cmd =========="
    # 执行命令并将结果重定向到文件，同时输出到控制台
    eval $cmd
done

# 记录测试总结束时间
echo -e "\n========== Test end time: $(date +"%Y-%m-%d %H:%M:%S") =========="

